<?php

class svnCache
{
	
	var $path = '';
	
	function svnCache()
	{
		//$Jconf = new JConfig();
		$this->path = JPATH_ROOT.DS.'cache'.DS;
	}
	
	function versionCheck($project)
	{
		if($this->has('svnVersionCheck'.$project))
		{
			if(!$this->expired('svnVersionCheck'.$project))
			{
				return $this->get('svnVersionCheck'.$project);
			}
		}
		return false;
	}
	
	function fetch($params,$toArray = false)
	{
		if($this->has($params))
		{
			return $this->get($params,$toArray);
		}
		
		return false;
	}
	
	
	function has($params)
	{
		$fname = $this->path . md5($params).'.cache';
		if(!file_exists($fname))
			return false;
		
		
		return true;
		
	}
	
	function expired($params)
	{
		$fname = $this->path .md5($params).'.cache';
		$time = strtotime("NOW -2 hours");
		if(filemtime($fname) < $time)
			return false;
		
		return true;
	}
	
	function get($params, $toarray = false)
	{
		$fname = $this->path .md5($params).'.cache';
		$res =  json_decode(file_get_contents($fname));
		if($toarray)
			return $this->toArray($res);
		else
			return $res;
	}
	
	function toArray($arr)
	{
		$return = array();
		if(is_object($arr) || is_array($arr))
		{
			foreach($arr as $k=>$v)
			{
				$return[$k] = $this->toArray($v);
			}
			return $return;
		}else{
			return $arr;
		}
		
	}
	
	function cache($params,$content)
	{
		
		$fname = $this->path . md5($params).'.cache';
		$fp = @fopen($fname, 'w+');
		if($fp)
		{
			fwrite($fp, json_encode($content));
			fclose($fp);
		}
	}
}
